home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / BEGINCPP.ARJ / #1.CPP < prev    next >
C/C++ Source or Header  |  1990-08-04  |  2KB  |  73 lines

  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. class String {
  5.         char *str;
  6.         static int count;
  7.   public:
  8.         String() { count++; str = new char; *str = 0; }
  9.         String( char * );
  10.         ~String() { delete str; }
  11.         operator char *();
  12.         int operator < (String s) { return strcmp(str, s.str) < 0; }
  13.         void print() { printf("%s", str); }
  14.  
  15.         friend int operator < (String, String);
  16.         friend void report() ;
  17. };
  18.  
  19. String::String(char *s)
  20. {
  21.         count++;
  22.         str = new char[strlen(s) + 1];
  23.         strcpy(str, s);
  24. }
  25.  
  26. String::operator char*() {
  27.         char *p = new char[strlen(str) + 1];
  28.         strcpy (p, str);
  29.         return p;        //use only a copy of str for protection
  30. }
  31.  
  32. int operator < (String s1, String s2)
  33. {
  34.        return strcmp (s1.str, s2.str);
  35. }
  36.  
  37. void report() 
  38. {
  39.        printf("Report on String usage: " );
  40.        printf(" %d Strings created\n", String::count);
  41. }
  42.  
  43. main()
  44. {
  45.         String s0 ;
  46.         String s1 ("s1 == \"Hello C\"\n");
  47.         String s2 ("s2 == \"Hello C++\"\n");
  48.         String *sp = new String( "Hello world!" );
  49.         
  50.         char *cp = (char *) *sp;        //same as *cp = *sp 
  51.  
  52.         if ( !strcmp(cp, (char *) *sp) )
  53.                printf("char *cp == (char *) *sp == \"%s\"\n", cp);
  54.  
  55.         s1.print();
  56.         s2.print();
  57.  
  58.         if(s1.operator < (s2))
  59.                printf("s1.operator < (s2)\n");
  60.         if(operator < (s1, s2))
  61.                printf("operator < (s1, s2)\n");
  62.         report();
  63. }
  64. /* output:
  65.  
  66. char *cp == (char *) *sp == "Hello world!"
  67. s1 == "Hello C"
  68. s2 == "Hello C++"
  69. s1.operator < (s2)
  70. operator < (s1, s2)
  71. Report on String usage:  4 Strings created
  72.  
  73. */